package com.southminority.ethnic.service.student.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.southminority.ethnic.controller.student.vo.AwardPageVo;
import com.southminority.ethnic.pojo.StudentAward;
import com.southminority.ethnic.service.student.StudentAwardService;
import com.southminority.ethnic.mapper.student.StudentAwardMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author SouthMinority
 * @description 针对表【student_award(学生获奖表)】的数据库操作Service实现
 * @createDate 2025-11-17
 */
@Service
public class StudentAwardServiceImpl extends ServiceImpl<StudentAwardMapper, StudentAward>
    implements StudentAwardService {

    @Override
    public Boolean incrementViews(Long id) {
        StudentAward award = this.getById(id);
        if (award != null) {
            award.setViews(award.getViews() == null ? 1 : award.getViews() + 1);
            return this.updateById(award);
        }
        return false;
    }

    @Override
    public Page<AwardPageVo> getAwardPage(Integer pageNum, Integer pageSize, String keyword, Integer status) {
        Page<StudentAward> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<StudentAward> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentAward::getIsDeleted, 0);
        
        // 状态筛选：如果status不为null，则按指定状态筛选；否则查询全部
        if (status != null) {
            queryWrapper.eq(StudentAward::getStatus, status);
        }
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like(StudentAward::getTitle, keyword)
                .or()
                .like(StudentAward::getStudentName, keyword)
                .or()
                .like(StudentAward::getAwardLevel, keyword)
            );
        }
        
        queryWrapper.orderByDesc(StudentAward::getAwardDate)
                   .orderByDesc(StudentAward::getCreateTime);
        
        Page<StudentAward> awardPage = this.page(page, queryWrapper);
        
        // 转换为VO，不包含完整描述
        Page<AwardPageVo> voPage = new Page<>(awardPage.getCurrent(), awardPage.getSize(), awardPage.getTotal());
        voPage.setRecords(awardPage.getRecords().stream().map(award -> {
            AwardPageVo vo = new AwardPageVo();
            BeanUtils.copyProperties(award, vo);
            return vo;
        }).toList());
        
        return voPage;
    }
}
